const PURCHASED_KEY = 'sunlake-purchased-courses'

const readPurchasedCourseIds = (): string[] => {
  if (typeof window === 'undefined') {
    return []
  }
  try {
    const raw = window.localStorage.getItem(PURCHASED_KEY)
    if (!raw) {
      return []
    }
    const parsed = JSON.parse(raw)
    return Array.isArray(parsed) ? parsed.filter((item) => typeof item === 'string') : []
  } catch (error) {
    console.warn('读取课程购买记录失败', error)
    return []
  }
}

const writePurchasedCourseIds = (ids: string[]) => {
  if (typeof window === 'undefined') {
    return
  }
  try {
    window.localStorage.setItem(PURCHASED_KEY, JSON.stringify(Array.from(new Set(ids))))
  } catch (error) {
    console.warn('写入课程购买记录失败', error)
  }
}

export const checkCourseAccess = async (courseId: string): Promise<{ purchased: boolean }> => {
  await new Promise((resolve) => setTimeout(resolve, 200))
  const purchasedIds = readPurchasedCourseIds()
  return { purchased: purchasedIds.includes(courseId) }
}

export const markCoursePurchased = async (courseId: string) => {
  const purchasedIds = readPurchasedCourseIds()
  purchasedIds.push(courseId)
  writePurchasedCourseIds(purchasedIds)
}

export const clearCoursePurchaseRecords = () => {
  if (typeof window === 'undefined') {
    return
  }
  window.localStorage.removeItem(PURCHASED_KEY)
}
